package kumiyunwii.kumi.controller;

//import com.alibaba.fastjson.JSONObject;
//import kumiyunwii.kumi.util.KumiUtil;
//import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
//import sun.jvm.hotspot.debugger.ThreadContext;

import javax.net.ssl.*;
//import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

@RestController
@RequestMapping("")
public class KumiController {

    private final static Executor executor = Executors.newCachedThreadPool();//启用多线程

    private final static String tenantId = "3b68411ec13d4666b9cfd9d9ddca07ff";

    private final static List<Integer> studentKeyIdss = new ArrayList<>();
    private final static Integer[] studentKeyId = {53743};

//    @ApiOperation(value = "发起微信支付")
    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public Map<String,String> test() throws Exception {
        String payXmlStr = "<xml><nonce_str>097e59dbbcbb43f39e48228b5db01009</nonce_str><out_trade_no>fb199ee3467f40b3886925df11dedd77</out_trade_no><openid>osuJY5OzUtj1LBxT-4ODPuLeCdWE</openid><appid>wxdf9844097c04d781</appid><total_fee>10</total_fee><sign>8824FF14397901F5650E0D0256BA9D1B</sign><trade_type>JSAPI</trade_type><attach>获取prepay_id</attach><body>buycourse</body><mch_id>1491491902</mch_id><notify_url>https://webboss.saas.vip/OperatorCourse/doWechatPayReturn</notify_url><spbill_create_ip>112.229.149.40</spbill_create_ip></xml>";
//        log.info("payXml is   " + payXmlStr);
        String responseXmlStr = sendPost("https://api.mch.weixin.qq.com/pay/unifiedorder", payXmlStr); //用该xml去微信接口请求数据
//        log.info("responseXmlStr is   " + responseXmlStr);
        System.out.println(responseXmlStr);
        Map<String,String> map = new HashMap<>();
        map.put("test",responseXmlStr);
        return map;
    }

    @RequestMapping(value = "/luyou", method = RequestMethod.GET)
    public Map<String,String> luyou() throws Exception {
            String UTF8 = "UTF-8";
            String reqBody = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><xml> " +
                    "<refund_desc>微预订用户取消订单退款！！</refund_desc> " +
                    "<nonce_str>9999b51c7df24640b60b48ae4e397f4b</nonce_str>" +
                    "<out_trade_no>f1d4651667eb4f18b59e77a9cf00eccd</out_trade_no>" +
                    "<out_refund_no>REFUND_f1d4651667eb4f18b59e77a9cf00eccd</out_refund_no>" +
                    "<total_fee>10</total_fee>" +
                    "<refund_fee>10</refund_fee>" +
                    "<appid>wx1a4f9d573c8c6603</appid>" +
                    "<sign>7280CFB6C5F060CBC687B274278390CE</sign>" +
                    "<mch_id>1491491902</mch_id>" +
                    "</xml>";

            char[] password = "1491491902".toCharArray();
//        FileInputStream instream = new FileInputStream(new File("/Users/ocean/Desktop/apiclient_cert.p12"));

            String p12fileUrl = "http://p7h4p0vv6.bkt.clouddn.com/FqLcJ8rX5f-nvvMpr_VV3-BXEIJ6?e=1531061447&token=yNjhOp7gnH4St9yP72OlwuQ6JUNQf49pxAuGWYFt:24WShSFsS2fsQ2kvOhUaLgVEibQ=";
//        if (p12fileUrl.contains("p7h4p0vv6.bkt.clouddn.com")) {
//            p12fileUrl = QiNiuUtil.getDownloadUrl(p12fileUrl);
//        }
            InputStream lin = null;
            HttpURLConnection conn = null;
            InputStream inputStream = null;
            // 建立链接
            URL httpUrl = new URL(p12fileUrl);
            conn = (HttpURLConnection) httpUrl.openConnection();
            //以Post方式提交表单，默认get方式
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            // post方式不能使用缓存
            conn.setUseCaches(false);
            //连接指定的资源
            conn.connect();
            //获取网络输入流
            inputStream = conn.getInputStream();

//         httpUrl = new URL("https://api.mch.weixin.qq.com/secapi/pay/refund");
            KeyStore ks = KeyStore.getInstance("PKCS12");
            byte[] arrsy = toByteArray(inputStream);
            ByteArrayInputStream certBis = new ByteArrayInputStream(arrsy);
//        log.info("byte is "+config.getCertStream() + "mchid is "+tenantOfProduct.getMchId() + " reqBody  is " + reqBody + "  "+connectTimeoutMs + "   "+readTimeoutMs+"  strUrl is "+strUrl);
            ks.load(certBis, password);

            // 实例化密钥库 & 初始化密钥工厂
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(ks, password);
            // 创建SSLContext
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(kmf.getKeyManagers(), null, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
            URL httpUrl1 = new URL("https://api.mch.weixin.qq.com/secapi/pay/refund");
            HttpURLConnection httpURLConnection = (HttpURLConnection) httpUrl1.openConnection();

            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setConnectTimeout(6000);
            httpURLConnection.setReadTimeout(8000);
            httpURLConnection.connect();
            OutputStream outputStream = httpURLConnection.getOutputStream();
            outputStream.write(reqBody.getBytes(UTF8));

            //获取内容
            InputStream inputStream1 = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream1, UTF8));
            final StringBuffer stringBuffer = new StringBuffer();
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line);
            }
            String resp = stringBuffer.toString();
            if (stringBuffer != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    // e.printStackTrace();
                }
            }
            if (inputStream1 != null) {
                try {
                    inputStream1.close();
                } catch (IOException e) {
                    // e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    // e.printStackTrace();
                }
            }
//        if (certStream != null) {
//            try {
//                certStream.close();
//            } catch (IOException e) {
//                // e.printStackTrace();
//            }
//        }
        Map<String,String> map = new HashMap<>();
            map.put("String",resp);
            return map;
    }
    public static byte[] toByteArray(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
        }
        output.toByteArray();
        return buffer;
    }

    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
//            log.info("httpUtil"+url);
//            log.info(param);
            if ("https".equalsIgnoreCase(realUrl.getProtocol())) {
                ignoreSsl();
            }
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("contentType", "utf-8");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            //conn.getOutputStream().write(param.getBytes(Charset.forName("utf-8")));
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
//            log.info("---------------------------");
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
//        log.info(result);
        return result;
    }

    public static void ignoreSsl() throws Exception{
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String urlHostName, SSLSession session) {
                System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
                return true;
            }
        };
        trustAllHttpsCertificates();
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
    }

    private static void trustAllHttpsCertificates() throws Exception {
        TrustManager[] trustAllCerts = new TrustManager[1];
        TrustManager tm = new miTM();
        trustAllCerts[0] = tm;
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }

    static class miTM implements TrustManager,X509TrustManager {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public boolean isServerTrusted(X509Certificate[] certs) {
            return true;
        }

        public boolean isClientTrusted(X509Certificate[] certs) {
            return true;
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType)
                throws CertificateException {
            return;
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType)
                throws CertificateException {
            return;
        }
    }

//    @RequestMapping(value = "/getExamQuestion")
//    public List<String> getExamQuestion() throws InterruptedException {
//        String url = "http://101.201.181.39:9087/kumi-web-party/examination/v3/getExamQuestion";//考生获取自己的试题列表接口
//        Map<String, Object> params = new TreeMap<>();
//        params.put("page",1);
//        params.put("pageSize",2000);
//        List<String> resultList = new ArrayList<>();
//        for (Integer studentId : studentKeyId) {
//            executor.execute(new Runnable() {
//                @Override
//                public void run() {
//                    //这里面写需要多线程执行对
//                    System.out.println(studentId);
//                    String result = KumiUtil.sendPost(url, params.toString(), tenantId, studentId);
//                    resultList.add(result);
//                }
//            });
//        }
//        Thread.sleep(300000);
////        String result = KumiUtil.sendPost(url, params.toString(), tenantId, 53996);
//        return resultList;
//    }
//
//    @RequestMapping(value = "/submitExamAnswerSequance")
//    public String submitExamAnswerSequance() {
//        String url = "http://101.201.181.39:9087/kumi-web-party/examination/submitExamAnswerSequance";//考生提交试题接口,5分钟提交一次
//        Map<String, Object> params = new TreeMap<>();
//        params.put("exam_keyId",171);
//        JSONObject jsonObject = new JSONObject();
//        StringBuffer sb = new StringBuffer("1:1");
//        for (int i = 1 ; i<1000; i++){
//            int numberAnswer = (int)(Math.random()*3) + 1;
//            sb.append(";"+ i + ":" +numberAnswer);
//        }
//        jsonObject.put("answerRecordStr",sb.toString());
//        params.put("answerRecordStr",jsonObject.toString());
//        for (Integer studentId : studentKeyId) {
//            executor.execute(new Runnable() {
//                @Override
//                public void run() {
//                    //这里面写需要多线程执行对
//                    String result = KumiUtil.sendPost(url, params.toString(), tenantId, studentId);
//
//                }
//            });
//        }
//        return "Hello! Docker!";
//    }
//
//    @RequestMapping(value = "/submitExamAnswerSequenceScore")
//    public String submitExamAnswerSequenceScore() {
//        String url = "http://101.201.181.39:9087/kumi-web-party/examination/submitExamAnswerSequenceScore";//考生提交试题并判分接口
//        Map<String, Object> params = new TreeMap<>();
//        params.put("exam_keyId",171);
//        JSONObject jsonObject = new JSONObject();
//        StringBuffer sb = new StringBuffer("1:1");
//        for (int i = 2 ; i<1000; i++){
//            int numberAnswer = (int)(Math.random()*3) + 1;
//            sb.append(";"+ i + ":" +numberAnswer);
//        }
//        jsonObject.put("answerRecordStr",sb.toString());
//        params.put("answerRecordStr",jsonObject.toString());
//        for (Integer studentId : studentKeyId) {
//            executor.execute(new Runnable() {
//                @Override
//                public void run() {
//                    //这里面写需要多线程执行对
//                    String result = KumiUtil.sendPost(url, params.toString(), tenantId, studentId);
//
//                }
//            });
//        }
//        return "Hello! Docker!";
//    }
//
//    @RequestMapping(value = "/sys/partyAffairs/exam/update/judgementQuestion")
//    public String judgementQuestion() {
//        String url = "http://101.201.181.39:9087/kumi-web-party/examination/sys/partyAffairs/exam/update/judgementQuestion";//判题的接口,一人一判
//        Map<String, Object> params = new TreeMap<>();
//        params.put("exam_keyId",171);
//        for (Integer studentId : studentKeyId) {
//            executor.execute(new Runnable() {
//                @Override
//                public void run() {
//                    //这里面写需要多线程执行对
//                    String result = KumiUtil.sendPost(url, params.toString(), tenantId, studentId);
//
//                }
//            });
//        }
//        return "OK!";
//    }
//
//    @RequestMapping(value = "/viewScore")
//    public Map<String, Object> viewScore() {
//        String url = "http://101.201.181.39:9087/kumi-web-party/examination/viewScore";//判题的接口,一人一判
//        Map<String, Object> params = new TreeMap<>();
//        params.put("exam_keyId",171);
//        for (Integer studentId : studentKeyId) {
//            executor.execute(new Runnable() {
//                @Override
//                public void run() {
//                    //这里面写需要多线程执行对
//                    String result = KumiUtil.sendPost(url, null, tenantId,studentId);
//                    params.put(studentId.toString(),result);
//                }
//            });
//        }
//        return params;
//    }


}

